<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title"
                style="text-align: center; display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="font-size: 18px; font-weight: bold; color: #333;">
                    {{ finished_goods_store.finished_goods_store_code }}
                </div>
                <div style=" height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handleAudit">审核</el-button>
                </div>
            </div>

            <hr style="border: 0; height: 1px; background: #e0e0e0; margin: 10px 0 20px;">
            <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                <tbody>

                    <!-- 第二行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库仓库</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.warehouse_name }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库库位</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.zone_name }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库员</td>
                        <td style="padding: 12px 15px;">{{ userValue(finished_goods_store.finished_goods_store_rep_id)
                        }}</td>
                    </tr>

                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库员部门</td>
                        <td style="padding: 12px 15px;">{{
                            deptValue(finished_goods_store.finished_goods_store_dept_id) }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            质检员</td>
                        <td style="padding: 12px 15px;">{{
                            finished_goods_store.quality_testing_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            质检状态</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.quality_testing_status == '0' ?
                            "不合格"
                            : finished_goods_store.quality_testing_status == '1' ? "部分合格" : "全部合格"
                        }}</td>
                    </tr>

                    <!-- 第六行 - 创建信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建人</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.create_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建时间</td>
                        <td style="padding: 12px 15px;" colspan="3">{{
                            finished_goods_store.create_time.replace('T', ' ') ||
                            '无'
                        }}</td>
                    </tr>

                    <!-- 第七行 - 修改信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改人</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.update_by == 'null' ? '暂无' :
                            finished_goods_store.update_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ finished_goods_store.update_time == 'null' ? '暂无' :
                                finished_goods_store.update_time.replace('T', ' ') }}
                        </td>
                    </tr>

                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核人</td>
                        <td style="padding: 12px 15px;">{{ finished_goods_store.finished_goods_store_audit_by == 'null'
                            ? '暂无' : finished_goods_store.finished_goods_store_audit_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ finished_goods_store.finished_goods_store_audit_time == 'null' ? '暂无' :
                                finished_goods_store.finished_goods_store_audit_time.replace('T', ' ') }}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">成品入库明细</h2>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }">
                <el-table-column prop="pro_name" label="产品名称" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="measure_id" label="单位">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="finished_goods_qty" label="成品数量" />
                <el-table-column prop="unqualified_qty" label="不合格数量" />
                <el-table-column prop="store_qty" label="入库数量" />
                <el-table-column prop="location_name" label="出库库位" />
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">成品总数量：{{ finished_goods_total_qty }} &nbsp;&nbsp;&nbsp;
                    不合格总数量：{{
                        unqualified_total_qty }} &nbsp;&nbsp;&nbsp;入库总数量：{{
                        store_total_qty }}&nbsp;&nbsp;&nbsp;质检状态：{{ finished_goods_store.quality_testing_status == '0' ?
                        "不合格"
                        : finished_goods_store.quality_testing_status == '1' ? "部分合格" : "全部合格"
                    }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw, markRaw, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage, handleEdit, ElMessageBox, ElLoading } from 'element-plus';
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import dayjs from 'dayjs'
export default {
    setup() {
        const finished_goods_store = reactive({
            finished_goods_store_id: 0,//成品入库主键
            finished_goods_store_code: "",//成品入库编号
            warehouse_code: "",//出库仓库编号
            warehouse_name: "",//出库仓库名称
            zone_code: "",//出库库区编号
            zone_name: "",//出库库区名称
            location_code: "",//出库库位编号
            location_name: "",//出库库位编号
            finished_goods_store_rep_id: "",//入库员id
            finished_goods_store_dept_id: "",//入库员部门
            finished_goods_store_time: "",//入库时间
            quality_testing_status: "",//质检状态
            create_by: "",//创建人
            create_time: "",//创建时间
            update_by: "",//修改人
            update_time: "",//修改时间
            finished_goods_store_audit_by: "",//审核人
            finished_goods_store_audit_time: "",//审核时间
            quality_testing_by: "",//质检人
            quality_testing_time: "",//质检时间
            finished_goods_store_audit_status: "",//审核状态
        })
        const userOptions = ref([])
        const deptOptions = ref([])
        const measureOptios = ref([])
        const store = useStore()
        const code = store.state.FinishedGoodsStoreCode
        const selectedData = ref([])
        const Weahouse = ref([])
        const Warhouse_zone = ref([])
        const Warehouse_location = ref([])
        const router = useRouter()
        const centerDialogVisible = ref(false)
        const auditStatus = ref('1')
        const auditOpinion = ref('')
        const finished_goods_store_id = ref()
        const finished_goods_total_qty = computed(() => {
            return selectedData.value.reduce((total, row) => {
                return total + (Number(row.finished_goods_qty) || 0)
            }, 0)
        })
        const unqualified_total_qty = computed(() => {
            return selectedData.value.reduce((total, row) => {
                return total + (Number(row.unqualified_qty) || 0)
            }, 0)
        })
        const store_total_qty = computed(() => {
            return selectedData.value.reduce((total, row) => {
                return total + (Number(row.store_qty) || 0)
            }, 0)
        })

        onMounted(async () => {
            getUser()
            getDept()
            getMeasure()
            getMeasure()
            // await WeahousesSelect()
            await finishedGoodsStoreFill()
        })

        async function finishedGoodsStoreFill() {
            try {
                const result = await axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/GetFG_Finished_Goods_StoreByCode", {
                    params: {
                        code: code
                    }
                })
                for (const key in finished_goods_store) {
                    // 排除数字类型字段（如 user_id、dept_id）
                    if (key === 'finished_goods_store_rep_id' || key === 'finished_goods_store_dept_id') {
                        finished_goods_store[key] = Number(result.data[key]); // 保留数字类型
                    } else if (key === 'finished_goods_store_time') {
                        finished_goods_store[key] = new Date(result.data[key]).toISOString();
                    } else {
                        finished_goods_store[key] = String(result.data[key]); // 其他字段转字符串
                    }
                }
                // await handleSelectChange(finished_goods_store.warehouse_code)

                // await handleSzone(finished_goods_store.zone_code)

                await finishedGoodsStoreDetailsFill()
            } catch (error) {
                console.info(error)
            }
        }

        async function finishedGoodsStoreDetailsFill() {
            const result = await axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/Get_Finished_Goods_Store_DetailsByCode", {
                params: { code: code }
            })
            selectedData.value = result.data.map(item => ({
                location_code: item.location_code,
                location_name: item.location_name,
                ...item,
            }))
        }

        // 查询仓库信息
        async function WeahousesSelect() {
            try {
                const result = await axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                Weahouse.value = result.data;
            } catch (err) {
                console.info(err)
            }
        }

        // 选择入库仓库事件触发
        const handleSelectChange = async (selectedValue) => {
            try {
                const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
                finished_goods_store.warehouse_name = selectedItem?.warehouse_name || "";

                const result = await axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
                    params: { warehouse_code: selectedValue },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                Warhouse_zone.value = result.data;
            } catch (err) {
                console.error("加载库区失败:", err);
                ElMessage.warning("仓库对应的库区加载失败");
            }
        };

        //选择入库库位时触发
        const handleSzone = async (value) => {
            try {
                const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value);
                finished_goods_store.zone_name = selectedItemzone?.zone_name || "";

                const result = await axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
                    params: { zone_code: value },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                Warehouse_location.value = result.data;
            } catch (err) {
                console.error("加载库位失败:", err);
                ElMessage.warning("库区对应的库位加载失败");
            }
        }

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getDept() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            const parentDept = deptOptions.value.find((dept) => dept.dept_id == row)
            return parentDept ? parentDept.dept_name : "无"
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOptions.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                measureOptios.value = [{
                    dict_value: "0", dict_label: "请选择单位"
                }, ...result.data]
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/FG/FinishedGoodsStore";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "成品入库",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        //编辑按钮
        function handleEdit() {
            if (finished_goods_store.finished_goods_store_audit_status != '0') {
                ElMessage.warning('已审核过的订单不允许再次编辑！')
                return
            }
            store.commit("FinishedGoodsStoreCode", finished_goods_store.finished_goods_store_code)
            router.push("/main/FG/FinishedGoodsStoreUpdate")
        }

        //点击删除
        function handleDelete() {
            if (finished_goods_store.finished_goods_store_audit_status != '0') {
                ElMessage.warning('已审核过的订单不允许进行删除！')
                return
            }
            ElMessageBox.confirm(
                '此操作将删除'+finished_goods_store.finished_goods_store_code+'信息，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    const loadingInstance = ElLoading.service({
                        lock: true,
                        text: '正在删除中...',
                        background: 'rgba(0, 0, 0, 0.7)',
                    });
                    axios.put("http://localhost:5181/api/FG_Finished_Goods_Store/FG_Finished_Goods_StoreDel", {
                        finished_goods_store_id: finished_goods_store.finished_goods_store_id,
                        del_flag: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.success('成品入库订单删除成功！')
                            fill();
                            count();
                        } else {
                            ElMessage({
                                type: 'danger',
                                message: '成品入库订单删除失败！'
                            });
                        }
                    }).catch((err) => {
                        console.info(err)
                    }).finally(() => {
                        loadingInstance.close();
                    })
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        //审核按钮
        function handleAudit() {
            if (finished_goods_store.finished_goods_store_audit_status != '0') {
                ElMessage.warning('已审核过的订单不允许再次审核！')
                return
            }
            centerDialogVisible.value = true
            finished_goods_store_id.value = finished_goods_store.finished_goods_store_id
        }

        //确定审核按钮
        function updateAudit() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在审核中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            axios.put("http://localhost:5181/api/FG_Finished_Goods_Store/FG_Finished_Goods_StoreUpdateAudit", {
                finished_goods_store_id: finished_goods_store_id.value,
                finished_goods_store_audit_by: localStorage.getItem('userLName'),
                finished_goods_store_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                finished_goods_store_audit_opinion: auditOpinion.value,
                finished_goods_store_audit_status: auditStatus.value
            }, {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    if (auditStatus.value == '1') {
                        ElMessage.success('审核通过')
                    } else if (auditStatus.value == '2') {
                        ElMessage.warning('审核已被驳回！')
                    }
                    close()
                    fill()
                    count()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '成品入库订单审核失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })
        }

        //关闭审核按钮
        function close() {
            auditOpinion.value = ""
            auditStatus.value = '1'
            centerDialogVisible.value = false
        }

        return {
            finished_goods_store, userValue, deptValue, userOptions, deptOptions, measureOptios, measureValue, selectedData, Weahouse, Warhouse_zone,
            Warehouse_location, finished_goods_total_qty, unqualified_total_qty, store_total_qty, handleClose, handleEdit, handleDelete, centerDialogVisible, auditOpinion, auditStatus,
            handleAudit, updateAudit, close, finished_goods_store_id
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}
</style>